package cn.chainco.cts.action;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import cn.chainco.cts.iservice.CommonManager;
import cn.chainco.cts.iservice.ICompanyManager;
import cn.chainco.cts.iservice.IEmployeeManager;
import cn.chainco.cts.iservice.IFeeManager;
import cn.chainco.cts.iservice.IItemManager;
import cn.chainco.cts.iservice.IUserManager;
import cn.chainco.cts.jdo.Company;
import cn.chainco.cts.jdo.DataDictionary;
import cn.chainco.cts.jdo.Employee;
import cn.chainco.cts.jdo.Item;
import cn.chainco.cts.jdo.User;
import cn.chainco.cts.jdo.Work;
import cn.chainco.cts.jdo.WorkDoc;
import cn.chainco.cts.jdo.WorkItem;
import cn.chainco.cts.utils.CommUtils;
import cn.chainco.cts.utils.Constants;
import cn.chainco.cts.utils.CookieUtil;
import cn.chainco.cts.utils.VarData;
import cn.chainco.cts.utils.query.Page;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@InterceptorRef("ctsInterceptors")
public class CtsAction extends ActionSupport {

	private User user;
	private Company company;
	private Item item;
	private DataDictionary dd;
	private IUserManager userManager;
	private ICompanyManager companyManager;
	private IItemManager itemManager;
	private IFeeManager feeManager;
	private CommonManager commonManager;
	private IEmployeeManager employeeManager;
	
	private Page pager;
	private int pageSize=15;
	private int pageNumber=1;
	
	@Action("index")
	public String index(){
		HttpServletRequest request = ServletActionContext.getRequest();
	    String userId = CookieUtil.getCookieValue(request, "cts_userid");
	    String usetype = request.getParameter("usetype");
	    String userId2 = request.getParameter("userId");
	    
	    if(usetype!=null && usetype.equals("1")){
	    	ActionUtil.clearUserByCookie();
	    	if(CommUtils.isCorrectNumber(userId2)){
	    		User _user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId2));
	    		request.setAttribute("user", _user);
	    		if(_user!=null){
	    			ActionUtil.addUserToCookie(_user, -1);
                    Company company1 = this.companyManager.findCompayByUser(_user);
                    
                    if(company1!=null){
                    	ActionUtil.addCompanyToCookie(company1, -1);
                    	Employee employee1 = this.employeeManager.findEmployeeByUser(_user, company1);
                    	if(employee1!=null){
                    		ActionUtil.addEmployeeToCookie(employee1, -1);
                    	}
                    }
	    		}
	    	}
	    }else{
	    	if(CommUtils.isCorrectNumber(userId)){
	    		User _user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
	    		request.setAttribute("user", _user);
	    	}
	    }
		
		ActionUtil.getTopAllInfo();
	    request.setAttribute("place", 1);
	    
		return "index";
	}
	
	@Action(value="findCtsInfo" , results={@Result(name="dd" , location="findDataDicationaryList" ,type="redirect")})
	public String findCtsInfo(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String ctstype = request.getParameter("ctstype"); // user , company , item
		String language = CookieUtil.getCookieValue(request, "cts_locale");
		String workKey = request.getParameter("workKey");
		
		String createTime = request.getParameter("createTime");
		String status = request.getParameter("status");
		String type = request.getParameter("type");
		String typeDetail = request.getParameter("typeDetail");
		
		String adminName = CookieUtil.getCookieValue(request, "cts_username");
		
		if(VarData.adminName.equals(adminName)){
			Integer l_status = (status!=null && status!="") ? Integer.valueOf(status) : null;
			
			if(ctstype == null || ctstype.equals("")){
				ctstype = "user";
			}
			
			if(ctstype.equals("user")){
				List<User> list = this.userManager.findUser(workKey, createTime, l_status, null);
				for(int i =0;i<list.size();i++){
					User user = list.get(i);
					if(user.getUserName().equals("admin")){
						list.remove(i);
					}
				}
				
				list = getPageList(list , request);
				request.setAttribute("list", list);
			}else if(ctstype.equals("company")){
				List<Company> list = this.companyManager.findCompany(workKey , null , createTime , null, l_status);
				list = getPageList(list , request);
				request.setAttribute("list", list);
			}else if(ctstype.equals("item")){
				ctstype = "";
				//List<Item> list = this.itemManager.findItem(null, "" , workKey , 0 , l_status);
				//request.setAttribute("list", list);
			}else if(ctstype.equals("data")){
				//request.setAttribute("workKey", workKey);
				//request.setAttribute("createTime", createTime);
				//request.setAttribute("status", status);
				//request.setAttribute("ctstype" , ctstype);
				//request.setAttribute("type", type);
				//request.setAttribute("typeDetail" , typeDetail);
				//request.setAttribute("pageSize" , pageSize);
				//request.setAttribute("pageNumber" , pageNumber);
				
				//return "dd"; // 重定向到DataDictionaryAction-findDataDicationaryList
			}
		}
		
		request.setAttribute("statusl1", request.getParameter("statusl1"));
		request.setAttribute("statusl2", request.getParameter("statusl2"));
		request.setAttribute("workKey", workKey);
		request.setAttribute("createTime", createTime);
		request.setAttribute("status", status);
		request.setAttribute("ctstype" , ctstype);
		return "cts/listCts";
	}
	
	private <E>List<E> getPageList(List<E> list , HttpServletRequest request){
		pager = new Page();
		pager.setElements(list);
		pager.setPageNumber(pageNumber);
		pager.setPageSize(pageSize);
		pager.setTotalElements(list.size());
	   
		request.setAttribute("pageCount", pager.getLastPageNumber());
	    return pager.getCurrentElements();
	}
	
	@Action("findSingleCtsInfo")
	public String findSingleCtsInfo(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String type = request.getParameter("type"); 
		String typeDetail = request.getParameter("typeDetail");
		String ctstype = request.getParameter("ctstype"); // user , company , item
		String id = request.getParameter("id");
		
		if(ctstype.equals("user")){
			user = this.commonManager.findEntityByPK(User.class, Long.valueOf(id));
		}else if(ctstype.equals("company")){
			if(CommUtils.isCorrectNumber(id)){
				company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(id));
			}
		}else if(ctstype.equals("item")){
			if(CommUtils.isCorrectNumber(id)){
				item = this.commonManager.findEntityByPK(Item.class, Long.valueOf(id));
			}
		}
		
		request.setAttribute("ctstype" , ctstype);
		request.setAttribute("id" , id);
		request.setAttribute("type", type);
		request.setAttribute("typeDetail", typeDetail);
		
		return "cts/addCts";
	}

	@Action("delCtsInfo")
	public void delCtsInfo(){
		HttpServletRequest request = ServletActionContext.getRequest();
		@SuppressWarnings("unused")
		String type = request.getParameter("type"); 
		@SuppressWarnings("unused")
		String typeDetail = request.getParameter("typeDetail");
		String ctstype = request.getParameter("ctstype"); // user , cpy , item
		String id = request.getParameter("id");
		
		if(CommUtils.isCorrectNumber(id)){
			if(ctstype.equals("user")){
				
				User _user = this.commonManager.findEntityByPK(User.class, Long.valueOf(id));
        		delWorkDocByUser(_user);
				int code = this.userManager.delUserByAll(_user);  // 删除用户和相联的数据
				if(code == 0){
					ActionUtil.outputData("0");
				}else{
					ActionUtil.outputData("1");
				}
				
			}else if(ctstype.equals("company")){
				
				Company _company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(id));
				delWorkDocByCompany(_company);
				int code = this.companyManager.delCompayByAll(_company);
				if(code == 0){
					ActionUtil.outputData("0");
				}else{
					ActionUtil.outputData("1");
				}
				
			}else if(ctstype.equals("item")){
				
				String sql = " select * from cts_workitem where 1=1 and itemId=%s ";
				sql = String.format(sql, id);
				List<WorkItem> workItemList = this.userManager.findSqlByElist(sql, WorkItem.class, null);
				if(workItemList.size() > 0){
					ActionUtil.outputData("2"); // 委托已使用
				}else{
					this.commonManager.deleteEntityByPK(Item.class, Long.valueOf(id));
					ActionUtil.outputData("1");
				}
				
			}
		}else{
			ActionUtil.outputData("0");
		}
	}
	
	
	/**
	 * 根据用户删除文档
	 * @param user
	 */
	@SuppressWarnings("unused")
	private void delWorkDocByUser(User user){
		List<Company> cpylist = ActionUtil.findListByE(Company.class , " 1=1 and userId="+user.getId());
		if(cpylist.size() > 0){
			Company _company = cpylist.get(0);
			delWorkDoc(_company , user); // 删除文档文件
		}
	}
	
	/**
	 * 根据公司删除文档
	 * @param company
	 */
	@SuppressWarnings("unused")
	private void delWorkDocByCompany(Company company){
       User user = this.companyManager.findEntityByPK(User.class, company.getUser().getId());
       if(user!=null){
    	   delWorkDoc(company , user); // 删除文档文件
       }
       
	}
	
	/**
	 * 删除文件档
	 * @param company
	 */
	@SuppressWarnings("unused")
	private void delWorkDoc(Company company , User user){
		/*String workSql = " companyId='"+company.getId()+"'";
		String emplySql = " userId="+user.getId() + " and companyId="+company.getId();
		List<Employee> emlist = ActionUtil.findListByE(Employee.class, emplySql);
		
		List<Work> worklist = ActionUtil.findListByE(Work.class, workSql);
		
		for (Employee employee : emlist) {
			String workSql2 = " employeeId="+employee.getId();
			List<Work> wlist = ActionUtil.findListByE(Work.class, workSql2);
			worklist.addAll(wlist);
		}
		
		for (Work work : worklist) {
			delDoc(company , work);
		}*/
		
		delDoc(company);

	}
	
	/**
	 * 删文档(删除公司的文档)
	 * @param docName
	 */
	private void delDoc(Company company){
	   try {
			String fileFolder = ServletActionContext.getServletContext().getRealPath(File.separator + Constants.BASE_DIR + File.separator +  Constants.WORK_FILE + File.separator +  company.getId());
			File file = new File(fileFolder);
			if(file.getName().equals(Constants.WORK_FILE)){
				return;
			}else if(file.exists()){
				ActionUtil.deleteFileX1(file);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Action("saveCtsInfo")
	public void saveCtsInfo(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String type = request.getParameter("type"); 
		String typeDetail = request.getParameter("typeDetail");
		String ctstype = request.getParameter("ctstype"); // user , cpy , item
		String id = request.getParameter("id");
		
		if(ctstype.equals("user")){
			
		}else if(ctstype.equals("cpy")){
			
		}else if(ctstype.equals("item")){
			 item.setCompany(null);
			 if(CommUtils.isCorrectNumber(id)){
			    this.commonManager.modifyEntity(item);
		     }else{
		    	 Long result = this.commonManager.saveEntity(item);
		    	 id = result.toString();
		     }
			 
			 ActionUtil.outputData("1");
		}
	}
	
	/**
	 * 切换语言
	 *
	 */
	@Action(value="changeLnaguage" , results={@Result(name="index" , location="index" ,type="redirect")})
	public String changeLnaguage(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String language = request.getParameter("language");
		
		int times = -1;
		if(CookieUtil.getCookieValue(request, "cts_times")!=""){
			times = Integer.valueOf(CookieUtil.getCookieValue(request, "cts_times"));
		}
		
		if("en".equals(language)){
			CookieUtil.addCookie(response, "cts_locale" , "en_US" , "/" , times);
		}else{
			CookieUtil.addCookie(response, "cts_locale" , "zh_CH" , "/" , times);
		}
		
		return "index";
	}
	
	
	@Action("modifyCtsStatus")
	public void modifyCtsStatus(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String statType = request.getParameter("statType");
		String id = request.getParameter("id");
		String status = request.getParameter("status");
		
		int code = 0;
		if(CommUtils.isCorrectNumber(id)){
			if(statType.equals("1")){
				User user = this.commonManager.findEntityByPK(User.class, Long.valueOf(id));
				user.setStatus(Integer.valueOf(status));
				this.commonManager.modifyEntity(user);
			}else if(statType.equals("2")){
				Company company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(id));
				company.setStatus(Integer.valueOf(status));
				this.commonManager.modifyEntity(company);
			}
			
			code = 1;
		}
		
		ActionUtil.outputData(code);
	}
	
	@Action("getTopPage")
	public String getTopPage(){
		ActionUtil.getTopAllInfo();
		return "top";
	}
	
	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public DataDictionary getDd() {
		return dd;
	}

	public void setDd(DataDictionary dd) {
		this.dd = dd;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public ICompanyManager getCompanyManager() {
		return companyManager;
	}

	public void setCompanyManager(ICompanyManager companyManager) {
		this.companyManager = companyManager;
	}

	public IFeeManager getFeeManager() {
		return feeManager;
	}

	public void setFeeManager(IFeeManager feeManager) {
		this.feeManager = feeManager;
	}

	public IItemManager getItemManager() {
		return itemManager;
	}

	public void setItemManager(IItemManager itemManager) {
		this.itemManager = itemManager;
	}

	public IUserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}

	public CommonManager getCommonManager() {
		return commonManager;
	}

	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public Page getPager() {
		return pager;
	}

	public void setPager(Page pager) {
		this.pager = pager;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public IEmployeeManager getEmployeeManager() {
		return employeeManager;
	}

	public void setEmployeeManager(IEmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}
	
	
	
}
